package com.kefu.web.im.config.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import com.kefu.web.im.config.IMDataContext;
import com.kefu.web.im.config.web.handle.AiIMEventHandler;
import com.kefu.web.im.config.web.handle.EntIMEventHandler;
import com.kefu.web.im.config.web.handle.IMEventHandler;
import com.kefu.web.im.config.web.handle.SeatEventHandler;

@Component
public class ServerRunner implements CommandLineRunner {
	private final SocketIOServer server;
	private final SocketIONamespace imSocketNameSpace;
	private final SocketIONamespace seatSocketIONameSpace;
	private final SocketIONamespace entIMSocketIONameSpace;
	private final SocketIONamespace aiIMSocketIONameSpace;

	@Autowired
	public ServerRunner(SocketIOServer server) {
		this.server = server;
		imSocketNameSpace = server.addNamespace(IMDataContext.NameSpaceEnum.IM.getNamespace());
		seatSocketIONameSpace = server.addNamespace(IMDataContext.NameSpaceEnum.SEAT.getNamespace());
		entIMSocketIONameSpace = server.addNamespace(IMDataContext.NameSpaceEnum.ENTIM.getNamespace());
		aiIMSocketIONameSpace = server.addNamespace(IMDataContext.NameSpaceEnum.AIIM.getNamespace());
	}

	@Bean(name = "imNamespace")
	public SocketIONamespace getIMSocketIONameSpace(SocketIOServer server) {
		imSocketNameSpace.addListeners(new IMEventHandler(server));
		return imSocketNameSpace;
	}

	@Bean(name = "seatNamespace")
	public SocketIONamespace getAgentSocketIONameSpace(SocketIOServer server) {
		seatSocketIONameSpace.addListeners(new SeatEventHandler(server));
		return seatSocketIONameSpace;
	}

	@Bean(name = "entimNamespace")
	public SocketIONamespace getEntIMSocketIONameSpace(SocketIOServer server) {
		entIMSocketIONameSpace.addListeners(new EntIMEventHandler(server));
		return entIMSocketIONameSpace;
	}

	@Bean(name = "aiimNamespace")
	public SocketIONamespace getAiIMSocketIONameSpace(SocketIOServer server) {
		aiIMSocketIONameSpace.addListeners(new AiIMEventHandler(server));
		return aiIMSocketIONameSpace;
	}

	public void run(String... args) throws Exception {
		server.start();
		IMDataContext.setIMServerStatus(true); // IMServer 启动成功
	}
}